<template>
	<view class="box">
		<!-- 选择会员 -->
		<view class="selectMember">
			<view class="member">
				<view @click="dialog = true">{{userName || '会员：'}}</view>
				<view style="position: relative;">{{userName?start_date:'汇总日期：'}}</view>
			</view>
			<view class="toSend" @click="creat">生成评估</view>
		</view>
		
		<!-- <view class="hasData" v-if="reData">
			<view v-for="(item,index) in allData" :key="index">
				<view class="summary" v-if="reData && reData[index] && reData[index].servId != 0">
					<image :src="'../../static/img/healthStatus/currentSummary/currentSummary'+(index+1)+'@2x.png'" class="topLeft"></image>
					<view class="top">
						<image src="@/static/img/quickly/healthStatus/number@2x.png"></image>
						<view>{{reData && reData[index] && reData[index].assessmentSn}}</view>
						<view>{{reData && reData[index] && reData[index].assessmentDate}}</view>
					</view>
					<view class="bottom">
						<view>{{userName}}</view>
						<view @click="detail(reData[index])">详情</view>
					</view>
				</view>
				<view class="noData" v-else>
					<image :src="'../../static/img/healthStatus/currentSummary/currentSummary'+(index+1)+'@2x.png'" class="topLeft"></image>
					无数据
				</view>
			</view>
		</view>
		<view class="metadata" v-else>
			<view class="case" v-for="(item,index) in allData" :key="index">
				<image src="@/static/img/healthStatus/currentSummary/metadata.png"></image>
				<view class="title">{{item}}</view>
				<view>无数据</view>
			</view>
		</view> -->
		<member :dialog.sync="dialog"  @hidedialog="hidedialog" @chooseUser="chooseUser"></member>
		<!-- <reportImg ref="reportImg" :info="info"></reportImg> -->
		<div id="pic">
			<div class="title1"><i></i>体重、BMI</div>
			<div id="main" style="height: 400px;"></div>
		</div>
		<div id="pic2">
			<div class="title1"><i></i>血压(舒张压、收缩压）</div>
			<div id="main2" style="height: 400px;"></div>
		</div>
		<div id="pic3">
			<div class="title1"><i></i>空腹血糖、餐后2h血糖</div>
			<div id="main3" style="height: 400px;"></div>
		</div>
		<div id="pic4">
			<div class="title1"><i></i>血脂（TC、TG、HDL-C、LDL-C）</div>
			<div id="main4" style="height: 400px;"></div>
		</div>
		<div id="pic5">
			<div class="title1"><i></i>尿酸</div>
			<div id="main5" style="height: 400px;"></div>
		</div>
	</view>
</template>

<script>
	import member  from '@/components/selectMember/selectMember.vue';
	import html2canvas from 'html2canvas'
	// import reportImg  from './reportImg.vue';
	export default{
		components:{member},
		data () {
			const currentDate = this.getDate({
				format: true
			})
			return {
				start:'',
				end:currentDate,
				start_date:currentDate,
				userName:'',
				dialog:false,
				allData:['会员基本信息','体检指标评估','生活方式评估','心理健康评估','健康素养评估','焦虑状态评估','抑郁状态评估'],
				reData: null,
				info:{},
				base64: []
			}
		},
		methods:{
			//关闭弹出框
			hidedialog(){
				this.dialog = false
			},
			//选择会员
			chooseUser(e){
				this.userId = e.userId;
				this.userName = e.userName;
				this.$api.summaryAssessmentControllerReportList(e.userId).then((res)=>{
					if(res.data.returnCode == 200){
						var Date = []
						var bodyIndexData = []
						var diastole = [] //舒张压
						var shrink = [] //收缩
						var ebloodsugar = [] //空腹血糖
						var twobloodsugar = [] //2小时血糖
						var TC = []
						var TG = []
						var HDLC = []
						var LDLC = []
						var uricacid = [] //尿酸
						res.data.result.map((a)=>{
							bodyIndexData.push(a.bodyIndex || 0)
							diastole.push(a.bloodPressure && a.bloodPressure.split('/') && a.bloodPressure.split('/')[1] || 0)
							shrink.push(a.bloodPressure && a.bloodPressure.split('/') && a.bloodPressure.split('/')[0] || 0)
							ebloodsugar.push(a.bloodGlucose || 0)
							twobloodsugar.push(a.towBloodGlucose || 0)
							TC.push(a.cholesterol || 0)
							TG.push(a.triacylglycerol || 0)
							HDLC.push(a.highCholesterol || 0)
							LDLC.push(a.lowCholesterol || 0)
							uricacid.push(a.bloodUricAcid || 0)
							Date.push(a.fillFormDate)
						})
						this.echarts1(Date,bodyIndexData)
						this.echarts2(Date,diastole,shrink)
						this.echarts3(Date,diastole,shrink)
						this.echarts4(Date,TC,TG,HDLC,LDLC)
						this.echarts5(Date,uricacid)
					}else{
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
				})
			},
			// 日期
			bindDateChange(e) { 
				this.start_date = e.target.value;
			},
			// 获取当前时间
			getDate(type) {
			   const date = new Date();
			   let year = date.getFullYear();
			   let month = date.getMonth() + 1;
			   let day = date.getDate();
			  
			   if (type === 'start') {
				year = year - 60;
			   } else if (type === 'end') {
				year = year + 2;
			   }
			   month = month > 9 ? month : '0' + month;;
			   day = day > 9 ? day : '0' + day;
			   return `${year}-${month}-${day}`;
			},
			// 体重BMI
			echarts1(Date,bodyIndexData){
				var chartDom = document.getElementById('main');
				var myChart = this.$echarts.init(chartDom);
				var option;
				option = {
					xAxis: {type: 'category',data: Date},
					yAxis: {
						min:0,
						max:bodyIndexData.sort()[1]+10,
						show: true,
						type: 'value',
						axisLine:{
							lineStyle:{color:{y: 0,y2: 1,type: 'linear',colorStops: [{offset: 0, color: '#FF0000'},{offset: 0.3, color: '#F39800'},{offset: 0.6, color: '#3DB51C'},{offset: .8, color: '#3366FF'}],}},
						}
					},
					series: [{data: bodyIndexData,type: 'line',symbol:'circle',itemStyle : {normal: {label : {show: true},width:1,color:"#CCCCCC"},}}]
				};
				option && myChart.setOption(option);
			},
			// 血压图
			echarts2(Date,data1,data2){
				var chartDom = document.getElementById('main2');
				var myChart = this.$echarts.init(chartDom);
				var option;
				option = {
					legend: {data: ['舒张压', '收缩压'],},
					xAxis: {type: 'category',data: Date},
					yAxis: {type: 'value'},
					series: [{name: '舒张压',type: 'line',data: data1},{name: '收缩压',type: 'line',data: data2}]
				};
				option && myChart.setOption(option);
			},
			// 血糖图
			echarts3(Date,data1,data2){
				var chartDom = document.getElementById('main3');
				var myChart = this.$echarts.init(chartDom);
				var option;
				option = {
					legend: {data: ['空腹血糖', '餐后2h血糖']},
					xAxis: {type: 'category',data: Date},
					yAxis: {type: 'value'},
					series: [{name: '空腹血糖',type: 'line',data: data1},{name: '餐后2h血糖',type: 'line',data: data2}]
				};
				option && myChart.setOption(option);
			},
			// 血脂
			echarts4(Date,TC,TG,HDLC,LDLC){
				var chartDom = document.getElementById('main4');
				var myChart = this.$echarts.init(chartDom);
				var option;
				option = {
					legend: {data: ['TC', 'TG', 'HDLC', 'LDLC']},
					xAxis: {type: 'category',data: Date},
					yAxis: {type: 'value'},
					series: [{name: 'TC',type: 'line',data: TC},{name: 'TG',type: 'line',data: TG},{name: 'HDLC',type: 'line',data: HDLC},{name: 'LDLC',type: 'line',data: LDLC}]
				};
				option && myChart.setOption(option);
			},
			// 血脂
			echarts5(Date,data){
				var chartDom = document.getElementById('main5');
				var myChart = this.$echarts.init(chartDom);
				var option;
				option = {
					legend: {data: ['尿酸']},
					xAxis: {type: 'category',data: Date},
					yAxis: {type: 'value'},
					series: [{name: '尿酸',type: 'line',data: data}]
				};
				option && myChart.setOption(option);
			},
			toImg(dom) {
				var dom = dom // 获取dom元素
				return new Promise((resolve,reject)=>{
					// 使页面滑到顶部，避免顶部出现白边
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 0
					})
					html2canvas(dom, {
						width: dom.clientWidth, //dom 原始宽度
						height: dom.clientHeight,
						scrollY: 0, // html2canvas默认绘制视图内的页面，需要把scrollY，scrollX设置为0
						scrollX: 0,
						useCORS: true, //支持跨域，但好像没什么用
					}).then((canvas) => {
						// 将生产的canvas转为base64图片
						if(dom.attributes[1].nodeValue == 'pic'){
							this.base64.push(canvas.toDataURL('image/png').replace('data:image/png;base64,',''))
						}else if(dom.attributes[1].nodeValue == 'pic2'){
							this.base64.push(canvas.toDataURL('image/png').replace('data:image/png;base64,',''))
						}else if(dom.attributes[1].nodeValue == 'pic3'){
							this.base64.push(canvas.toDataURL('image/png').replace('data:image/png;base64,',''))
						}else if(dom.attributes[1].nodeValue == 'pic4'){
							this.base64.push(canvas.toDataURL('image/png').replace('data:image/png;base64,',''))
						}else if(dom.attributes[1].nodeValue == 'pic5'){
							this.base64.push(canvas.toDataURL('image/png').replace('data:image/png;base64,',''))
						}
						resolve(true)
					});
				})
			},
			// 图片转base64
			image2Base64(img) {
			    var canvas = document.createElement("canvas");
			    canvas.width = 500;
			    canvas.height = 707;
			    var ctx = canvas.getContext("2d");
			    ctx.drawImage(img, 0, 0, 500, 707);
			    var dataURL = canvas.toDataURL("image/png");
			    return dataURL;
			},
			creat(){
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				})
				const _this = this;
				var img = new Image();
				img.src="../../static/img/reportFrist.png";
				img.onload=function(){
					const base64 = _this.image2Base64(img);
					_this.base64.push(base64.replace('data:image/png;base64,',''))
				}
				this.toImg(document.querySelector('#pic')).then((a)=>{
					if(a){
						this.toImg(document.querySelector('#pic2')).then((b)=>{
							if(b){
								this.toImg(document.querySelector('#pic3')).then((c)=>{
									if(c){
										this.toImg(document.querySelector('#pic4')).then((d)=>{
											if(d){
												this.toImg(document.querySelector('#pic5')).then((e)=>{
													this.$api.summaryAssessmentControllerAdd(this.userId,{image:_this.base64}).then((res)=>{
														window.location.href = 'http://health.jlm12580.com/web/viewer.html?file='+res.data.result.url
													})
												})
											}
										})
									}
								})
							}
						})
					}
				})
				
				// let _this = this;
				// if(!this.userId) {
				// 	uni.showToast({
				// 		title:'请选择会员',
				// 		icon:'none'
				// 	})
				// 	return
				// }
				// if(!this.start_date) {
				// 	uni.showToast({
				// 		title:'请选择日期',
				// 		icon:'none'
				// 	})
				// 	return
				// }
				// const data = this.reData.filter((a)=>{
				// 	return a.assessmentSn != null
				// })
				// const defaultData = data.filter((a)=>{
				// 	return a.title == '会员基本信息'
				// })
				// if(defaultData.length <= 0){
				// 	uni.showToast({
				// 		title:'请先完善会员基本信息。',
				// 		icon:'none'
				// 	})
				// 	return
				// }
				// if(data.length <= 1){
				// 	uni.showToast({
				// 		title:'用户至少存在一份评估才可生成汇总。',
				// 		icon:'none'
				// 	})
				// 	return
				// }
				// uni.pageScrollTo({
				// 	scrollTop:0
				// })
				// this.$api.appAssessSummaryxzhzReport(this.userId,data).then((res)=>{
				// 	if(res.data.returnCode == 200){
				// 		this.info = res.data.result
				// 		setTimeout(()=>{
				// 			_this.$refs.reportImg.toImg().then((base64)=>{
				// 				var arr = base64.split(',')
				// 				var mime = arr[0].match(/:(.*?);/)[1]
				// 				var bstr = atob(arr[1]) 
				// 				var nn = bstr.length 
				// 				var u8arr = new Uint8Array(nn);
				// 				while(nn--){
				// 					u8arr[nn] = bstr.charCodeAt(nn);
				// 				}
				// 				var obj = new Blob([u8arr], {type:mime});
				// 				_this.$refs.reportImg.toImg2().then((base642)=>{
				// 					var arr = base642.split(',')
				// 					var mime = arr[0].match(/:(.*?);/)[1]
				// 					var bstr = atob(arr[1]) 
				// 					var nn = bstr.length 
				// 					var u8arr = new Uint8Array(nn);
				// 					while(nn--){
				// 						u8arr[nn] = bstr.charCodeAt(nn);
				// 					}
				// 					var obj2  = new Blob([u8arr], {type:mime});
				// 					var formData = new FormData()
				// 					formData.append('file1', obj)  
				// 					formData.append('file2', obj2)  
				// 					_this.$api.appAssessSummaryUpload(res.data.result.id,formData).then((ares)=>{
				// 						if(ares.data.returnCode == 200){
				// 							uni.navigateTo({
				// 								url:'/pages/currentSummary/list'
				// 							})
				// 						}
				// 					})
				// 				})
				// 			})
				// 		},500)
				// 	}else{
				// 		uni.showToast({
				// 			title:res.data.message,
				// 			icon: 'none'
				// 		})
				// 	}
				// })
			}
		}
	}
</script>
<style lang="scss" scoped>
	#pic6{
		position: absolute;
		top: -10000px;
		image{
			width: 800px;
		}
	}
	#pic,#pic2,#pic3,#pic4,#pic5{
		width: 800px;
		position: absolute;
		top: -10000px;
		.title1{
			font-size: 48rpx;
			color: #00B25C;
			font-weight: bold;
			margin-bottom: 20rpx;
			margin-left: 30rpx;
		}
		.title2{
			background: #00C481;
			color: #fff;
			font-size: 33rpx;
			display: flex;
			align-items: center;
			padding: 10rpx 0 10rpx 15rpx;
			i{
				display: inline-block;
				width: 5rpx;
				height: 16rpx;
				background: #fff;
				margin-right: 15rpx;
			}
		}
	}
</style>
<style lang="scss" scoped>
	@import '@/static/css/quickly/healthStatus/common.scss';
	.selectMember {
		display: flex;
		.member {
			flex: 1;
			display: flex;
			view {
				width: 200upx;
			}
			view:nth-of-type(2) {
				flex: 1;
				margin-left: 0 !important;
			}
		}
	}
	.hasData,.metadata {
		width: 702upx;
		margin: 130upx 24upx;
		padding-top: 24upx;
		.summary {
			width: 702upx;
			background: #FFFFFF;
			border-radius: 12upx;
			position: relative;
			padding: 0 28upx 0 42upx;
			box-sizing: border-box;
			margin-bottom: 24upx;
			.topLeft {
				position: absolute;
				left: 0;
				width: 278upx;
				height: 56upx;
				margin-bottom: 32upx;
			}
			.top {
				padding-top: 86upx;
				display: flex;
				position: relative;		
				border-bottom: 1upx solid #cccccc;
				padding-bottom: 24upx;
				image {
					position: absolute;
					left: -48upx;
					top: 61%;
					width: 32upx;
					height: 30upx;
				}
				view {
					flex: 1;
				}
				view:last-child{
					text-align: right;
				}
			}
			.bottom {
				display: flex;
				padding: 25upx 0 35upx;
				view:nth-child(1) {
					flex: 1;
					color: #333333;
					font-size: 40upx;
					font-weight: bold;
				}
				view:last-child {
					width: 146upx;
					height: 50upx;
					background: #6AB7FF;
					border-radius: 25upx;
					color: #FFFFFF;
					font-size: 30upx;
					line-height: 50upx;
					text-align: center;
				}
			}
		}
	}
	
	.noData {
		width: 702upx;
		height: 96upx;
		background: #FFFFFF;
		border-radius: 12upx;
		position: relative;
		color: #677092;
		font-size: 32upx;
		text-align: right;
		padding-right: 34upx;
		box-sizing: border-box;
		line-height: 96upx;
		margin-bottom: 24upx;
		.topLeft {
			position: absolute;
			left: 0;
			top: 0;
			width: 278upx;
			height: 56upx;
			margin-bottom: 32upx;
		}
	}
	
	.metadata {
		.case {
			width: 702upx;
			height: 96upx;
			background: #FFFFFF;
			border-radius: 12upx;
			display: flex;
			align-items: center;
			padding: 0 34upx 0 0;
			box-sizing: border-box;
			margin-bottom: 24upx;
			image {
				width: 6upx;
				height: 20upx;
			}
			.title {
				flex: 1;
				color: #05C6AD;
				font-size: 34upx;
				font-weight: bold;
				padding-left: 38upx;
			}
			view:last-child {
				flex: 1;
				text-align: right;
				color: #677092;
				font-size: 32upx;
			}
		}
	}
</style>
